package ClientsAndHotels;

import jade.core.AID;
import jade.core.behaviours.TickerBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class CalendarAgent extends BaseAgent {
    public static final String NEW_DAY_CONVERSATION = "new-day";
    private static final long DAY_IN_MILLIS = 10000;

    private static int instances = 0;

    private Date date = Utils.createDate(new Date());

    @Override
    protected void setup() {
        synchronized (CalendarAgent.class) {
            instances++;
            if (instances > 1) {
                log("W systemie jest już kalendarz");
                doDelete();
                return;
            }
        }
        addBehaviour(new TickerBehaviour(this, DAY_IN_MILLIS) {

            @Override
            protected void onTick() {
                startNewDay();
            }
        });

        super.setup();
    }

    @Override
    protected void takeDown() {
        synchronized (CalendarAgent.class) {
            instances--;
        }
        super.takeDown();
    }

    private List<AID> getObservers() {
        ArrayList<AID> result = new ArrayList<AID>();
        DFAgentDescription template = new DFAgentDescription();
        ServiceDescription sd = new ServiceDescription();
        sd.setType(CalendarObserverAgent.TYPE);
        template.addServices(sd);
        try {
            DFAgentDescription[] descriptions = DFService
                    .search(this, template);
            for (DFAgentDescription d : descriptions) {
                result.add(d.getName());
            }
        } catch (FIPAException e) {
            e.printStackTrace();
        }
        return result;
    }

    private void startNewDay() {
        ACLMessage message = new ACLMessage(ACLMessage.INFORM);
        for (AID observer : getObservers()) {
            message.addReceiver(observer);
        }
        message.setLanguage("JavaSerialization");
        message.setConversationId(NEW_DAY_CONVERSATION);
        try {
            message.setContentObject(date);
            send(message);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DAY_OF_YEAR, 1);
            date = calendar.getTime();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
